package main

import (
	"RedisLock/connect/rds"
	"context"
	"fmt"
	"github.com/redis/go-redis/v9"
	"log/slog"
	"time"
)

func main() {
	var err error
	var conn *redis.Conn
	var hashs map[string]string
	ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(time.Second*3))
	defer cancel()
	//获取客户端
	client := rds.Client("127.0.0.1:6379", "")
	//获取连接
	conn, err = rds.Conn(ctx, client)
	if err != nil {
		slog.Error(err.Error())
	}
	//加载脚本
	scrips := make(map[string]string)
	scrips["load"] = `if redis.call("GET", KEYS[1]) == ARGV[1] then redis.call("SET", KEYS[1], ARGV[1], "PX", ARGV[2]) return "OK" else return redis.call("SET", KEYS[1], ARGV[1], "NX", "PX", ARGV[2]) end`
	scrips["unload"] = `if redis.call("GET",KEYS[1])==ARGV[1] then return redis.call("DEL",KEYS[1]) else return 0 end`
	hashs, err = rds.LoadScripts(ctx, client, scrips)
	if err != nil {
		slog.Error(err.Error())
		return
	}
	//测试示例
	fmt.Println(hashs)
	//获取分布式锁
	fmt.Println(conn.EvalSha(ctx, hashs["load"], []string{"hello"}, 123456, 10000).Result())
	//重复分布式锁
	fmt.Println(conn.EvalSha(ctx, hashs["load"], []string{"hello"}, 123456, 10000).Result())
	//抢分布式锁失败
	fmt.Println(conn.EvalSha(ctx, hashs["load"], []string{"hello"}, 1234, 10000).Result())
	//解锁
	fmt.Println(conn.EvalSha(ctx, hashs["unload"], []string{"hello"}, 123456).Result())
	//抢分布式锁成功
	fmt.Println(conn.EvalSha(ctx, hashs["load"], []string{"hello"}, 1234, 10000).Result())
}
